package com.uduemc.biso.node.web.component.operate;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.uduemc.biso.core.extities.center.SysContainerType;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModel;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModelAction;
import com.uduemc.biso.node.core.operate.entities.OperateLog;

@Aspect
@Component
public class OperateLoggerActionController extends OperateLoggerController {

//	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.ActionController.save(..))", returning = "returnValue")
//	public void save(JoinPoint point, Object returnValue) throws IOException {
//		if (!JsonResult.code200((JsonResult) returnValue)) {
//			return;
//		}
//		Object[] args = point.getArgs();
//		Signature signature = point.getSignature();
//		String declaringTypeName = signature.getDeclaringTypeName();
//		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
//		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//				OperateLoggerStaticModelAction.PUBLISH);
//
//		// 参数1
//		String paramString = objectMapper.writeValueAsString(args[0]);
//		RequestPublishData requestPublishData = objectMapper.readValue(paramString, RequestPublishData.class);
//
//		String dataBodyJson = null;
//		try {
//			dataBodyJson = NodeAESForJS.de(requestPublishData.getDataBody());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		if (StringUtils.isEmpty(dataBodyJson)) {
//			throw new RuntimeException("未能解析请求的body体！");
//		}
//
//		// 发布数据体
//		DataBody dataBody = null;
//		try {
//			dataBody = objectMapper.readValue(dataBodyJson, DataBody.class);
//		} catch (JsonParseException e) {
//			e.printStackTrace();
//		} catch (JsonMappingException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//		if (dataBody == null) {
//			throw new RuntimeException("未能解析请求的数据！");
//		}
//
//		PageService pageServiceImpl = SpringContextUtils.getBean("pageServiceImpl", PageService.class);
//		SPage sPage = pageServiceImpl.getInfoById(dataBody.getPageId());
//		if (sPage == null) {
//			throw new RuntimeException("未能获取到 SPage 数据！pageId: " + dataBody.getPageId());
//		}
//		String content = "发布页面（" + sPage.getName() + "）";
//
//		String returnValueString = objectMapper.writeValueAsString(returnValue);
//		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
//		insertOperateLog(log);
//
//		PageBannerData pageBanner = dataBody.getPageBanner();
//		if (pageBanner != null) {
//			content = "编辑Banner（" + sPage.getName() + "）";
//
//			paramString = objectMapper.writeValueAsString(pageBanner);
//			modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//					OperateLoggerStaticModelAction.UPDATE_BANNER);
//			log = makeOperateLog(modelName, modelAction, content, paramString, "");
//			insertOperateLog(log);
//		}
//
//		ContainerTypeService containerTypeServiceImpl = SpringContextUtils.getBean("containerTypeServiceImpl",
//				ContainerTypeService.class);
//		ComponentTypeService componentTypeServiceImpl = SpringContextUtils.getBean("componentTypeServiceImpl",
//				ComponentTypeService.class);
//		ContainerService containerServiceImpl = SpringContextUtils.getBean("containerServiceImpl",
//				ContainerService.class);
//		ComponentService componentServiceImpl = SpringContextUtils.getBean("componentServiceImpl",
//				ComponentService.class);
//		List<SysContainerType> sysContainerTypeList = containerTypeServiceImpl.getInfos();
//
//		ContainerData containerData = dataBody.getContainerData();
//
//		List<ContainerDataItemInsert> insertListContainerDataItemInsert = containerData.getInsertList();
//		if (!CollectionUtils.isEmpty(insertListContainerDataItemInsert)) {
//			Iterator<ContainerDataItemInsert> iteratorContainerDataItemInsert = insertListContainerDataItemInsert
//					.iterator();
//			while (iteratorContainerDataItemInsert.hasNext()) {
//				ContainerDataItemInsert containerDataItemInsert = iteratorContainerDataItemInsert.next();
//				String typename = containerDataItemInsert.getTypename();
//				SysContainerType sysContainerType = findSysContainerType(typename, sysContainerTypeList);
//				String name = containerDataItemInsert.getName();
//				content = "新增容器（" + (StringUtils.hasText(name) ? "容器名：" + name + " " : "") + "类型："
//						+ sysContainerType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(containerDataItemInsert);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.INSERT_CONTAINER);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<ContainerDataItemUpdate> updateListContainerDataItemUpdate = containerData.getUpdateList();
//		if (!CollectionUtils.isEmpty(updateListContainerDataItemUpdate)) {
//			Iterator<ContainerDataItemUpdate> iteratorContainerDataItemUpdate = updateListContainerDataItemUpdate
//					.iterator();
//			while (iteratorContainerDataItemUpdate.hasNext()) {
//				ContainerDataItemUpdate containerDataItemUpdate = iteratorContainerDataItemUpdate.next();
//				String typename = containerDataItemUpdate.getTypename();
//				SysContainerType sysContainerType = findSysContainerType(typename, sysContainerTypeList);
//				String name = containerDataItemUpdate.getName();
//				content = "编辑容器（" + (StringUtils.hasText(name) ? "容器名：" + name + " " : "") + "类型："
//						+ sysContainerType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(containerDataItemUpdate);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.UPDATE_CONTAINER);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<ContainerDataItemDelete> deleteListContainerDataItemDelete = containerData.getDeleteList();
//		if (!CollectionUtils.isEmpty(deleteListContainerDataItemDelete)) {
//			Iterator<ContainerDataItemDelete> iteratorContainerDataItemDelete = deleteListContainerDataItemDelete
//					.iterator();
//			while (iteratorContainerDataItemDelete.hasNext()) {
//				ContainerDataItemDelete containerDataItemDelete = iteratorContainerDataItemDelete.next();
//				long id = containerDataItemDelete.getId();
//				SContainer sContainer = containerServiceImpl.getInfoById(id);
//				if (sContainer == null) {
//					throw new RuntimeException("未能找到对应的容器的数据！id：" + id);
//				}
//				SysContainerType sysContainerType = findSysContainerType(sContainer.getTypeId(), sysContainerTypeList);
//				String name = sContainer.getName();
//				content = "删除容器（" + (StringUtils.hasText(name) ? "容器名：" + name + " " : "") + "类型："
//						+ sysContainerType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(containerDataItemDelete);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.DELETE_CONTAINER);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		ComponentData componentData = dataBody.getComponentData();
//
//		List<ComponentDataItemInsert> insertListComponentDataItemInsert = componentData.getInsertList();
//		if (!CollectionUtils.isEmpty(insertListComponentDataItemInsert)) {
//			Iterator<ComponentDataItemInsert> iteratorComponentDataItemInsert = insertListComponentDataItemInsert
//					.iterator();
//			while (iteratorComponentDataItemInsert.hasNext()) {
//				ComponentDataItemInsert componentDataItemInsert = iteratorComponentDataItemInsert.next();
//				long typeId = componentDataItemInsert.getTypeId();
//				String name = ""; // componentDataItemInsert.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "新增组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(componentDataItemInsert);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.INSERT_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<ComponentDataItemUpdate> updateListComponentDataItemUpdate = componentData.getUpdateList();
//		if (!CollectionUtils.isEmpty(updateListComponentDataItemUpdate)) {
//			Iterator<ComponentDataItemUpdate> iteratorComponentDataItemUpdate = updateListComponentDataItemUpdate
//					.iterator();
//			while (iteratorComponentDataItemUpdate.hasNext()) {
//				ComponentDataItemUpdate componentDataItemUpdate = iteratorComponentDataItemUpdate.next();
//				long typeId = componentDataItemUpdate.getTypeId();
//				String name = ""; // componentDataItemUpdate.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "编辑组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(componentDataItemUpdate);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.UPDATE_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<ComponentDataItemDelete> deleteListComponentDataItemDelete = componentData.getDeleteList();
//		if (!CollectionUtils.isEmpty(deleteListComponentDataItemDelete)) {
//			Iterator<ComponentDataItemDelete> iteratorComponentDataItemDelete = deleteListComponentDataItemDelete
//					.iterator();
//			while (iteratorComponentDataItemDelete.hasNext()) {
//				ComponentDataItemDelete componentDataItemDelete = iteratorComponentDataItemDelete.next();
//				long id = componentDataItemDelete.getId();
//				SComponent sComponent = componentServiceImpl.getInfoById(id);
//				if (sComponent == null) {
//					throw new RuntimeException("未能找到对应的组件的数据！id：" + id);
//				}
//				long typeId = sComponent.getTypeId();
//				String name = ""; // sComponent.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "删除组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(componentDataItemDelete);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.DELETE_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		PublishFormData formData = dataBody.getFormData();
//		formDataLog(modelName, declaringTypeName, formData);
//	}
//
//	protected void formDataLog(String modelName, String declaringTypeName, PublishFormData formData)
//			throws IOException {
//		ComponentTypeService componentTypeServiceImpl = SpringContextUtils.getBean("componentTypeServiceImpl",
//				ComponentTypeService.class);
//		ComponentService componentServiceImpl = SpringContextUtils.getBean("componentServiceImpl",
//				ComponentService.class);
//		FormService formServiceImpl = SpringContextUtils.getBean("formServiceImpl", FormService.class);
//		String paramString = "";
//		String modelAction = "";
//		String content = "";
//		OperateLog log = null;
//
//		FComponentData formComponentData = formData.getComponentData();
//
//		List<FComponentDataItemInsert> insertListFComponentDataItemInsert = formComponentData.getInsertList();
//		if (!CollectionUtils.isEmpty(insertListFComponentDataItemInsert)) {
//			Iterator<FComponentDataItemInsert> iteratorFComponentDataItemInsert = insertListFComponentDataItemInsert
//					.iterator();
//			while (iteratorFComponentDataItemInsert.hasNext()) {
//				FComponentDataItemInsert fComponentDataItemInsert = iteratorFComponentDataItemInsert.next();
//				long typeId = fComponentDataItemInsert.getTypeId();
//				String name = ""; // fComponentDataItemInsert.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "新增表单组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(fComponentDataItemInsert);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.INSERT_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<FComponentDataItemUpdate> updateListFComponentDataItemUpdate = formComponentData.getUpdateList();
//		if (!CollectionUtils.isEmpty(updateListFComponentDataItemUpdate)) {
//			Iterator<FComponentDataItemUpdate> iteratorFComponentDataItemUpdate = updateListFComponentDataItemUpdate
//					.iterator();
//			while (iteratorFComponentDataItemUpdate.hasNext()) {
//				FComponentDataItemUpdate fComponentDataItemUpdate = iteratorFComponentDataItemUpdate.next();
//				long typeId = fComponentDataItemUpdate.getTypeId();
//				String name = "";// fComponentDataItemUpdate.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "编辑表单组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//
//				paramString = objectMapper.writeValueAsString(fComponentDataItemUpdate);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.UPDATE_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<FComponentDataItemDelete> deleteListFComponentDataItemDelete = formComponentData.getDeleteList();
//		if (!CollectionUtils.isEmpty(deleteListFComponentDataItemDelete)) {
//			Iterator<FComponentDataItemDelete> iteratorFComponentDataItemDelete = deleteListFComponentDataItemDelete
//					.iterator();
//			while (iteratorFComponentDataItemDelete.hasNext()) {
//				FComponentDataItemDelete fComponentDataItemDelete = iteratorFComponentDataItemDelete.next();
//				long id = fComponentDataItemDelete.getId();
//				SComponentForm sComponentForm = componentServiceImpl.getInfoComponentFormById(id);
//				if (sComponentForm == null) {
//					throw new RuntimeException("未能找到对应的表单组件的数据！id：" + id);
//				}
//
//				long typeId = sComponentForm.getTypeId();
//				String name = ""; // sComponentForm.getName();
//				SysComponentType sysComponentType = componentTypeServiceImpl.getInfoById(typeId);
//
//				content = "删除表单组件（" + (StringUtils.hasText(name) ? "组件名：" + name + " " : "") + "类型："
//						+ sysComponentType.getName() + "）";
//				paramString = objectMapper.writeValueAsString(fComponentDataItemDelete);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.DELETE_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		FQuoteFormData quoteFormData = formData.getQuoteFormData();
//		List<FQuoteFormDataItemSave> saveQuoteForm = quoteFormData.getSaveQuoteForm();
//		if (!CollectionUtils.isEmpty(saveQuoteForm)) {
//			Iterator<FQuoteFormDataItemSave> iteratorFQuoteFormDataItemSave = saveQuoteForm.iterator();
//			while (iteratorFQuoteFormDataItemSave.hasNext()) {
//				FQuoteFormDataItemSave fQuoteFormDataItemSave = iteratorFQuoteFormDataItemSave.next();
//				long formId = fQuoteFormDataItemSave.getFormId();
//				SForm sForm = formServiceImpl.getInfo(formId);
//				if (sForm == null) {
//					throw new RuntimeException("未能找到对应的表单数据！formId：" + formId);
//				}
//				String name = sForm.getName();
//
//				content = "添加系统表单（" + "表单：" + name + "）";
//				paramString = objectMapper.writeValueAsString(fQuoteFormDataItemSave);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.INSERT_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//
//		List<FQuoteFormDataItemDelete> deleteQuoteForm = quoteFormData.getDeleteQuoteForm();
//		if (!CollectionUtils.isEmpty(deleteQuoteForm)) {
//			Iterator<FQuoteFormDataItemDelete> iteratorFQuoteFormDataItemDelete = deleteQuoteForm.iterator();
//			while (iteratorFQuoteFormDataItemDelete.hasNext()) {
//				FQuoteFormDataItemDelete fQuoteFormDataItemDelete = iteratorFQuoteFormDataItemDelete.next();
//				long formId = fQuoteFormDataItemDelete.getFormId();
//				SForm sForm = formServiceImpl.getInfo(formId);
//				if (sForm == null) {
//					throw new RuntimeException("未能找到对应的表单数据！formId：" + formId);
//				}
//				String name = sForm.getName();
//
//				content = "删除系统表单（" + "表单：" + name + "）";
//				paramString = objectMapper.writeValueAsString(fQuoteFormDataItemDelete);
//				modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
//						OperateLoggerStaticModelAction.DELETE_COMPONENT);
//				log = makeOperateLog(modelName, modelAction, content, paramString, "");
//				insertOperateLog(log);
//			}
//		}
//	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.ComponentController.updateCurrentComponentFixed(..))", returning = "returnValue")
	public void updateCurrentComponentFixed(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		String declaringTypeName = "com.uduemc.biso.node.web.api.controller.ActionController";
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.UPDATE_COMPONENT);

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);

		String content = "编辑网站漂浮组件";

		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}

	protected SysContainerType findSysContainerType(String typename, List<SysContainerType> sysContainerTypeList) {
		List<SysContainerType> collect = sysContainerTypeList.stream().filter(element -> {
			return element.getType().equals(typename);
		}).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(collect)) {
			throw new RuntimeException("未能找到对应的 SysContainerType 通过 typename: " + typename);
		}
		return collect.get(0);
	}

	protected SysContainerType findSysContainerType(long typeId, List<SysContainerType> sysContainerTypeList) {
		List<SysContainerType> collect = sysContainerTypeList.stream().filter(element -> {
			return element.getId().longValue() == typeId;
		}).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(collect)) {
			throw new RuntimeException("未能找到对应的 SysContainerType 通过 typeId: " + typeId);
		}
		return collect.get(0);
	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.SiteController.updateSiteTheme(..))", returning = "returnValue")
	public void updateSiteTheme(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		String declaringTypeName = "com.uduemc.biso.node.web.api.controller.ActionController";
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.UPDATE_THEMPLATE);

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);

		String content = "修改当前主题（" + paramString + "）";

		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.SiteController.updateSiteThemeColor(..))", returning = "returnValue")
	public void updateSiteThemeColor(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		String declaringTypeName = "com.uduemc.biso.node.web.api.controller.ActionController";
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.UPDATE_THEMPLATE);

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);

		String content = "修改当前主题颜色（" + paramString + "）";

		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}
}
